﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.BLL.Cached;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums;
using ZBJF.Warranty.Common.Enums.Api;
using ZBJF.Warranty.Common.Enums.Certificate;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.CommonObject.CardInfo;
using ZBJF.Warranty.PinanAPI;
using ZBJF.Warranty.PinanAPI.Model;
using ZBJF.Warranty.WebApiSite.Filter;
using ZBJF.Warranty.WebApiSite.Models.ForApp.Request;
using ZBJF.Warranty.WebApiSite.Models.ForApp.Response;
using ZBJF.Warranty.WebProvider;
using ZBJF.Warranty.WebProvider.InsuranceProducts;

namespace ZBJF.Warranty.WebApiSite.Controllers
{
    [ZBJFProviderAuthentication]
    public class WarrantyForAppController : ApiController
    {
        private string GetKeyValue(System.Web.HttpRequest request)
        {
            string keyValue = string.Empty;
            NameValueCollection getCollection = request.QueryString;

            if (getCollection == null || getCollection.Count <= 0)
            {
                if (request.Url != null)
                {
                    var seq = request.Url.Segments;
                    getCollection = new NameValueCollection
                    {
                        {SecuritySignHelper.Key, seq[seq.Length - 1].Trim('/')},
                    };
                }
            }
            if (getCollection != null && getCollection.Count > 0)
            {
                keyValue = getCollection[SecuritySignHelper.Key];
            }
            return keyValue;
        }

        private string GetSecrectKey(System.Web.HttpRequest request)
        {
            var keyValue = GetKeyValue(request);
            var apiConfig = AppConfigCached.GetApiPlatformConfig(keyValue);
            if (apiConfig != null)
                return apiConfig.SecrectKey;
            return string.Empty;
        }

        ///// <summary>
        ///// 发送短信接口 JSON {"Phones":"","Message":""}
        ///// </summary>
        ///// <returns></returns>
        //[System.Web.Http.ActionName("SendSMS")]
        //[System.Web.Http.HttpPost]
        //public object SendSMS()
        //{
        //    SendSMSRequestEntity value = null;
        //    StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
        //    String readData = reader.ReadToEnd();

        //    CommonMethod.WriteLogs("SendSMS-Data：" + readData);

        //    var data = SecuritySignHelper.DESDecrypt(readData, GetSecrectKey(System.Web.HttpContext.Current.Request));

        //    CommonMethod.WriteLogs("SendSMS-Data：" + data);

        //    value = (SendSMSRequestEntity)JSON.Decode(data, typeof(SendSMSRequestEntity));
        //    try
        //    {
        //        //判断参数 合法性
        //        if (string.IsNullOrEmpty(value.Phones) || string.IsNullOrEmpty(value.Message))
        //        {
        //            //参数有误
        //            return
        //                new SendSMSReturnEntity
        //                {
        //                    ResultCode = (int)ApiResultCode.ParaError,
        //                    ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ParaError)
        //                };
        //        }

        //        var resMsg = string.Empty;
        //        var result = BLL.SMS.SMSHelper.SendVerificationCodeSMS(value.Phones, value.Message, ref resMsg);
        //        return
        //            new SendSMSReturnEntity
        //            {
        //                ResultCode = result ? (int)ApiResultCode.Success : (int)ApiResultCode.ServerError,
        //                ResultMessage =
        //                    result
        //                        ? EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.Success)
        //                        : EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
        //            };
        //    }
        //    catch (Exception ex)
        //    {
        //        CommonMethod.WriteLogs("SendSMS-Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);
        //        return new SendSMSReturnEntity
        //        {
        //            ResultCode = (int)ApiResultCode.ServerError,
        //            ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
        //        };
        //    }
        //}
        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <returns></returns>
        [System.Web.Http.ActionName("SendVerificationCode")]
        [System.Web.Http.HttpPost]
        public object SendVerificationCode()
        {
            SendVerificationCodeRequestEntity value = null;
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            String readData = reader.ReadToEnd();

            CommonMethod.WriteLogs("SendVerificationCode-Data：" + readData);

            var data = SecuritySignHelper.DESDecrypt(readData, GetSecrectKey(System.Web.HttpContext.Current.Request));

            CommonMethod.WriteLogs("SendVerificationCode-Data：" + data);

            value = (SendVerificationCodeRequestEntity)JSON.Decode(data, typeof(SendVerificationCodeRequestEntity));
            try
            {
                //判断参数 合法性
                if (string.IsNullOrEmpty(value.Phone))
                {
                    //参数有误
                    return
                        new SendVerificationCodeReturnEntity
                        {
                            ResultCode = (int)ApiResultCode.ParaError,
                            ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ParaError)
                        };
                }

                var r = new Random();
                int code = r.Next(100000, 999999);
                //1.写入发送记录
                var addFlag=ServiceFactory.SendSmsVerificationCodeLogServiceInstance.AddSendVerificationCode(value.Phone,
                    code.ToString());
                if (addFlag)
                {
                    var resMsg = string.Empty;
                    var result = BLL.SMS.SMSHelper.SendVerificationCodeSMS(value.Phone, code.ToString(), ref resMsg);
                    return
                        new SendVerificationCodeReturnEntity
                        {
                            ResultCode = result ? (int) ApiResultCode.Success : (int) ApiResultCode.ServerError,
                            ResultMessage =
                                result
                                    ? EnumHelper.Instance.GetDescription(typeof (ApiResultCode), ApiResultCode.Success)
                                    : EnumHelper.Instance.GetDescription(typeof (ApiResultCode),
                                        ApiResultCode.ServerError)
                        };
                }
                else
                {
                    CommonMethod.WriteLogs("SendVerificationCode-Add Send SMS-Error.");
                    return new SendVerificationCodeReturnEntity
                    {
                        ResultCode = (int)ApiResultCode.ServerError,
                        ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
                    };
                }
            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("SendVerificationCode-Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);
                return new SendVerificationCodeReturnEntity
                {
                    ResultCode = (int)ApiResultCode.ServerError,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
                };
            }
        }
        /// <summary>
        /// 验证卡号密码
        /// </summary>
        /// <returns></returns>

        [System.Web.Http.ActionName("ValidateCardInfo")]
        [System.Web.Http.HttpPost]
        public object ValidateCardInfo()
        {
            ValidateCardInfoRequestEntity value = null;
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            String readData = reader.ReadToEnd();

            CommonMethod.WriteLogs("ValidateCardInfo-Data：" + readData);

            var data = SecuritySignHelper.DESDecrypt(readData, GetSecrectKey(System.Web.HttpContext.Current.Request));

            CommonMethod.WriteLogs("ValidateCardInfo-Data：" + data);

            value = (ValidateCardInfoRequestEntity)JSON.Decode(data, typeof(ValidateCardInfoRequestEntity));
            try
            {
                //判断参数 合法性
                if (string.IsNullOrEmpty(value.CardNo)||string.IsNullOrEmpty(value.CardPassword))
                {
                    //参数有误
                    return
                        new ValidateCardInfoReturnEntity
                        {
                            ResultCode = (int)ApiResultCode.ParaError,
                            ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ParaError)
                        };
                }
                CardInfoReturnEntity cardInfoReturnEntity = new CardInfoReturnEntity();
                var flag = InsuranceProductOrderCardProvider.GetInstance()
                    .ValidateCardInfo(value.CardNo, value.CardPassword, ref cardInfoReturnEntity);
                if (flag)
                {
                    return new ValidateCardInfoReturnEntity
                    {
                        Validatecertificate =
                            SecuritySignHelper.GetMD5_32(value.CardNo + value.CardPassword +
                                                         GetKeyValue(System.Web.HttpContext.Current.Request)),
                        ResultCode = (int) ApiResultCode.Success,
                        ResultMessage =
                            EnumHelper.Instance.GetDescription(typeof (ApiResultCode), ApiResultCode.Success)
                    };
                }
                else
                {

                    return new ValidateCardInfoReturnEntity
                    {
                        Validatecertificate = String.Empty,
                        ResultCode = (int)ApiResultCode.CardInfoInvalid,
                        ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.CardInfoInvalid)
                    };
                }
                
            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("ValidateCardInfo-Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);
                return new ValidateCardInfoReturnEntity
                {
                    ResultCode = (int)ApiResultCode.ServerError,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
                };
            }
        }

        [System.Web.Http.ActionName("CreatePolicy")]
        [System.Web.Http.HttpPost]
        public object CreatePolicy()
        {
            CreatePolicyRequestEntity value = null;
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            String readData = reader.ReadToEnd();

            CommonMethod.WriteLogs("CreatePolicy-Data：" + readData);

            var data = SecuritySignHelper.DESDecrypt(readData, GetSecrectKey(System.Web.HttpContext.Current.Request));

            CommonMethod.WriteLogs("CreatePolicy-Data：" + data);
            string msg = string.Empty;
            value = (CreatePolicyRequestEntity)JSON.Decode(data, typeof(CreatePolicyRequestEntity));
            try
            {
                //判断参数 合法性
                if (
                    //string.IsNullOrEmpty(value.CardNo) ||
                    //string.IsNullOrEmpty(value.CardPassword) ||
                    string.IsNullOrEmpty(value.Validatecertificate) ||
                    string.IsNullOrEmpty(value.UserName) ||
                    string.IsNullOrEmpty(value.UserPhone) ||
                    string.IsNullOrEmpty(value.CertificateNO) ||
                    string.IsNullOrEmpty(value.ValidateCode) ||
                    string.IsNullOrEmpty(value.ProductBrandName) ||
                    string.IsNullOrEmpty(value.ProductModelName) ||
                    (string.IsNullOrEmpty(value.IMEI) && string.IsNullOrEmpty(value.IDFV)))
                {
                    //参数有误
                    return
                        new CreatePolicyReturnEntity
                        {
                            ResultCode = (int) ApiResultCode.ParaError,
                            ResultMessage =
                                EnumHelper.Instance.GetDescription(typeof (ApiResultCode), ApiResultCode.ParaError)
                        };
                }

                //验证验证码  ValidateCode


                if (!string.IsNullOrEmpty(value.CardNo) && !string.IsNullOrEmpty(value.CardPassword))
                {
                    #region 新增

                    //1.校验卡密和校验凭证是否对得上
                    //2.校验卡密是否合法

                    #region 校验凭证

                    var validateCerti =
                        SecuritySignHelper.GetMD5_32(value.CardNo + value.CardPassword +
                                                     GetKeyValue(HttpContext.Current.Request));
                    if (value.Validatecertificate != validateCerti)
                    {
                        return
                            new CreatePolicyReturnEntity
                            {
                                ResultCode = (int) ApiResultCode.ValidateCertificateError,
                                ResultMessage =
                                    EnumHelper.Instance.GetDescription(typeof (ApiResultCode),
                                        ApiResultCode.ValidateCertificateError)
                            };
                    }

                    #endregion

                    CardInfoReturnEntity cardInfoReturnEntity = new CardInfoReturnEntity();
                    #region 卡密是否合法

                    var flag = InsuranceProductOrderCardProvider.GetInstance()
                    .ValidateCardInfo(value.CardNo, value.CardPassword, ref cardInfoReturnEntity);
                    if (!flag)
                    {
                        return
                            new CreatePolicyReturnEntity
                            {
                                ResultCode = (int)ApiResultCode.CardInfoInvalid,
                                ResultMessage =
                                    EnumHelper.Instance.GetDescription(typeof(ApiResultCode),
                                        ApiResultCode.CardInfoInvalid)
                            };
                    }
                    #endregion


                    var entity = ServiceFactory.InsuranceOrderServiceInstance.AddEntities(new InsuranceOrder
                    {
                        #region Init
                        CardNo = value.CardNo,
                        CardPwd = value.CardPassword,
                        VerificationCertificate = value.Validatecertificate,
                        OrderNO = CommonMethod.GetNewOrderNo(),
                        InsuranceCategoryName =
                            string.IsNullOrEmpty(value.InsuranceCategoryName) ? "碎屏险" : value.InsuranceCategoryName,
                        ProductName = string.IsNullOrEmpty(value.ProductName) ? "平安手机碎屏损失保险" : value.ProductName,
                        BuyType = value.BuyType ?? (byte) InsuranceBuyType.ActivationCodeBuy,
                        Price = value.Price,
                        WaitDays = cardInfoReturnEntity.WaitDays,
                        EffectiveDate = value.EffectiveDate,
                        PolicyPeriod = cardInfoReturnEntity.PolicyPeriod,
                        PolicyPeriodUnit = cardInfoReturnEntity.PolicyPeriodUnit,
                        UserName = value.UserName,
                        UserPhone = value.UserPhone,
                        CertificateType = value.CertificateType ?? (byte) UserCertificateType.IdentityCard,
                        CertificateNO = value.CertificateNO,
                        ProductTypeName = string.IsNullOrEmpty(value.ProductTypeName) ? "手机" : value.ProductTypeName,
                        IMEI = value.IMEI,
                        IDFV = value.IDFV,
                        ProductBrandName = value.ProductBrandName,
                        ProductModelName = value.ProductModelName,
                        RandomCode = value.RandomCode,
                        OrderStatus = (byte) InsuranceOrderStatus.Create,
                        OrderFromType = (byte) InsuranceOrderFromType.FromApp,
                        CreateOrderTime = DateTime.Now,
                        CardFromType=(byte)cardInfoReturnEntity.InsuranceCardType,
                        CreateBy = "AppAPI",
                        LastModifyBy = "AppAPI",
                        LastModifyTime = DateTime.Now
                        #endregion
                    });
                    if (entity.ID > 0)
                    {
                        ServiceFactory.InsuranceOrderImageServiceInstance.AddEntities(new InsuranceOrderImage
                        {
                            InsuranceOrderId = entity.ID,
                            ImageType = (byte) InsuranceImageType.Insurance,
                            ImageUrl = CommonMethod.SaveBase64Image(AppConfigCached.GetAppConfig().UploadFileVirtualPath, value.ImageData),
                            CreateBy="API",
                            CreateTime = DateTime.Now
                        });
                        return new CreatePolicyReturnEntity
                        {
                            ResultCode = (int) ApiResultCode.Success,
                            ResultMessage =
                                EnumHelper.Instance.GetDescription(typeof (ApiResultCode),
                                    ApiResultCode.Success)
                        };
                    }
                    return new CreatePolicyReturnEntity
                    {
                        ResultCode = (int)ApiResultCode.CreateOrderFaild,
                        ResultMessage =
                            EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.CreateOrderFaild)
                    };

                    #endregion
                }
                else
                {
                    var order = ServiceFactory.InsuranceOrderServiceInstance.LoadByIMEIOrIDFV(value.IMEI) ??
                                ServiceFactory.InsuranceOrderServiceInstance.LoadByIMEIOrIDFV(value.IDFV);
                    if (order != null)
                    {
                        #region Init
                        if (!string.IsNullOrEmpty(value.InsuranceCategoryName))
                            order.InsuranceCategoryName = value.InsuranceCategoryName;
                        if (!string.IsNullOrEmpty(value.ProductName))
                            order.ProductName = value.ProductName;
                        if (!string.IsNullOrEmpty(value.UserName))
                            order.UserName = value.UserName;
                        if (!string.IsNullOrEmpty(value.UserPhone))
                            order.UserPhone = value.UserPhone;
                        if (value.CertificateType.HasValue)
                            order.CertificateType = value.CertificateType.Value;
                        if (!string.IsNullOrEmpty(value.CertificateNO))
                            order.CertificateNO = value.CertificateNO;
                        if (!string.IsNullOrEmpty(value.ProductTypeName))
                            order.ProductTypeName = value.ProductTypeName;
                        if (!string.IsNullOrEmpty(value.ProductBrandName))
                            order.ProductBrandName = value.ProductBrandName;
                        if (!string.IsNullOrEmpty(value.ProductModelName))
                            order.ProductModelName = value.ProductModelName;
                        order.OrderFromType = (byte) InsuranceOrderFromType.FromApp;
                        order.LastModifyBy = "API";
                        order.LastModifyTime = DateTime.Now;
                        #endregion

                        if (ServiceFactory.InsuranceOrderServiceInstance.UpdateEntities(order))
                        {
                            if (!string.IsNullOrEmpty(value.ImageData))
                            {
                                ServiceFactory.InsuranceOrderImageServiceInstance.AddEntities(new InsuranceOrderImage
                                {
                                    InsuranceOrderId = order.ID,
                                    ImageType = (byte)InsuranceImageType.Insurance,
                                    ImageUrl = CommonMethod.SaveBase64Image(AppConfigCached.GetAppConfig().UploadFileVirtualPath, value.ImageData),
                                    CreateBy = "API",
                                    CreateTime = DateTime.Now
                                });
                            }
                            return new CreatePolicyReturnEntity
                            {
                                ResultCode = (int)ApiResultCode.Success,
                                ResultMessage =
                                    EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.Success)
                            };
                        }
                    }
                    return new CreatePolicyReturnEntity
                    {
                        ResultCode = (int)ApiResultCode.OrderInexistence,
                        ResultMessage =
                            EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.OrderInexistence)
                    };
                }
            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("ValidateCardInfo-Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);
                return new CreatePolicyReturnEntity
                {
                    ResultCode = (int)ApiResultCode.ServerError,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
                };
            }
        }

        [System.Web.Http.ActionName("GetPolicyInfo")]
        [System.Web.Http.HttpPost]
        public object GetPolicyInfo()
        {
            GetPolicyInfoRequestEntity value = null;
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            String readData = reader.ReadToEnd();

            CommonMethod.WriteLogs("GetPolicyInfo-Data：" + readData);

            var data = SecuritySignHelper.DESDecrypt(readData, GetSecrectKey(System.Web.HttpContext.Current.Request));

            CommonMethod.WriteLogs("GetPolicyInfo-Data：" + data);

            value = (GetPolicyInfoRequestEntity)JSON.Decode(data, typeof(GetPolicyInfoRequestEntity));
            try
            {
                //判断参数 合法性
                if (string.IsNullOrEmpty(value.SearchNO))
                {
                    //参数有误
                    return
                        new GetPolicyInfoReturnEntity
                        {
                            ResultCode = (int)ApiResultCode.OrderInexistence,
                            ResultMessage =
                                EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.OrderInexistence)
                        };
                }
                var order = ServiceFactory.InsuranceOrderServiceInstance.LoadByIMEIOrIDFV(value.SearchNO);
                if (order != null)
                {
                    return new
                    {
                        ResultCode = (int)ApiResultCode.Success,
                        ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.Success),
                        Data = new
                        {
                            order.UserName,
                            order.UserPhone,
                            order.CertificateType,
                            order.CertificateNO,
                            order.IMEI,
                            order.IDFV,
                            order.ProductBrandName,
                            order.ProductModelName,
                            order.OrderStatus
                        }
                    };
                }
                return new
                {
                    ResultCode = (int) ApiResultCode.Success,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof (ApiResultCode), ApiResultCode.Success),
                    Data = string.Empty
                };

            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("GetPolicyInfo-Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);
                return new GetPolicyInfoReturnEntity
                {
                    ResultCode = (int)ApiResultCode.ServerError,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
                };
            }
        }

        [System.Web.Http.ActionName("CreateAccident")]
        [System.Web.Http.HttpPost]
        public object CreateAccident()
        {
            CreateAccidentRequestEntity value = null;
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            String readData = reader.ReadToEnd();

            CommonMethod.WriteLogs("CreateAccident-Data：" + readData);

            var data = SecuritySignHelper.DESDecrypt(readData, GetSecrectKey(System.Web.HttpContext.Current.Request));

            CommonMethod.WriteLogs("CreateAccident-Data：" + data);

            value = (CreateAccidentRequestEntity)JSON.Decode(data, typeof(CreateAccidentRequestEntity));
            try
            {
                //判断参数 合法性
                if (string.IsNullOrEmpty(value.OrderPhone)||
                    string.IsNullOrEmpty(value.CertificateNO) ||
                    string.IsNullOrEmpty(value.Reporter) ||
                    string.IsNullOrEmpty(value.ReporterPhone) ||
                    value.ProvinceId <=0||
                    value.CityId <=0||
                    string.IsNullOrEmpty(value.AccidentAddress) ||
                    string.IsNullOrEmpty(value.AccidentProsess) ||
                    value.ExpectAccidentDate >DateTime.MinValue||
                    value.ImageList.Count<=0)
                {
                    //参数有误
                    return
                        new GetPolicyInfoReturnEntity
                        {
                            ResultCode = (int)ApiResultCode.OrderInexistence,
                            ResultMessage =
                                EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.OrderInexistence)
                        };
                }
                string msg = string.Empty;
                // 可能会有并发问题 TODO
                long orderId = 0;
                if (ServiceFactory.InsuranceOrderServiceInstance.ValidateCreateAccident(value.OrderPhone,
                    value.CertificateNO,out orderId, ref msg))
                {
                    var entity=ServiceFactory.InsuranceWarrantyRecordServiceInstance.AddEntities(new InsuranceWarrantyRecord
                    {
                        InsuranceOrderId = orderId,
                        WarrantyRecordNo = "B" + CommonMethod.GetNewOrderNo(),
                        Reporter = value.Reporter,
                        ReporterPhone = value.ReporterPhone,
                        ContactName = value.Reporter,
                        ContactPhone = value.ReporterPhone,
                        ExpectAccidentDate = value.ExpectAccidentDate,
                        ProvinceId = value.ProvinceId,
                        CityId = value.CityId,
                        AccidentAddress = value.AccidentAddress,
                        AccidentProsess = value.AccidentProsess,
                        SendUserName = value.SendUserName,
                        SendUserPhone = value.SendUserPhone,
                        SendUserAddress = value.SendUserAddress,
                        Status = (byte)InsuranceWarrantyStatus.Created,
                        CreateBy = "API",
                        CreateTime = DateTime.Now,
                        LastModifyBy = "API",
                        LastModifyTime = DateTime.Now
                    });
                    if (entity.ID > 0)
                    {
                        foreach (var item in value.ImageList)
                        {
                            ServiceFactory.InsuranceWarrantyRecordImagesServiceInstance.AddEntities(
                                new InsuranceWarrantyRecordImages
                                {
                                    InsuranceWarrantyRecordId = entity.ID,
                                    ImageType = item.ImageType,
                                    FilePath = CommonMethod.SaveBase64Image(AppConfigCached.GetAppConfig().UploadFileVirtualPath, item.ImageData),
                                    FileName = "App上传",
                                    FileSize = string.Empty,
                                    IsAvailable = true,
                                    CreateBy = "API",
                                    CreateTime = DateTime.Now
                                });
                        }

                        return new
                        {
                            ResultCode = (int)ApiResultCode.Success,
                            ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.Success)
                        };
                    }
                    else
                    {
                        return new
                        {
                            ResultCode = (int)ApiResultCode.ServerError,
                            ResultMessage = "保修失败."
                        };
                    }
                }
                else
                {
                    return new
                    {
                        ResultCode = (int) ApiResultCode.CreateAccidentError,
                        ResultMessage = msg
                    };
                }
            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("CreateAccident-Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);
                return new
                {
                    ResultCode = (int)ApiResultCode.ServerError,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
                };
            }
        }

        [System.Web.Http.ActionName("GetProvince")]
        [System.Web.Http.HttpPost]
        public object GetProvince()
        {
            try
            {
                return new
                {
                    ResultCode = (int) ApiResultCode.Success,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof (ApiResultCode), ApiResultCode.Success),
                    ProvinceList =
                        ServiceFactory.D_ProvinceServiceInstance.LoadEntities(c => true).ToList().Select(item => new
                        {
                            item.ProvinceID,
                            item.ProvinceName
                        })
                };
            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("GetProvince-Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);
                return new
                {
                    ResultCode = (int)ApiResultCode.ServerError,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
                };
            }
        }

        [System.Web.Http.ActionName("GetCity")]
        [System.Web.Http.HttpPost]
        public object GetCity()
        {
            GetCityRequestEntity value = null;
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            String readData = reader.ReadToEnd();

            CommonMethod.WriteLogs("GetCity-Data：" + readData);

            var data = SecuritySignHelper.DESDecrypt(readData, GetSecrectKey(System.Web.HttpContext.Current.Request));

            CommonMethod.WriteLogs("GetCity-Data：" + data);

            value = (GetCityRequestEntity)JSON.Decode(data, typeof(GetCityRequestEntity));
            try
            {
                //判断参数 合法性
                if (value.ProvinceId<=0)
                {
                    //参数有误
                    return
                        new
                        {
                            ResultCode = (int) ApiResultCode.ParaError,
                            ResultMessage =
                                EnumHelper.Instance.GetDescription(typeof (ApiResultCode), ApiResultCode.ParaError)
                        };
                }
                return new
                {
                    ResultCode = (int) ApiResultCode.Success,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof (ApiResultCode), ApiResultCode.Success),
                    CityList =
                        ServiceFactory.D_CityServiceInstance.LoadEntities(c => c.ProvinceID == value.ProvinceId)
                            .ToList()
                            .Select(item => new
                            {
                                item.CityID,
                                item.CityName
                            })
                };
            }
            catch (Exception ex)
            {
                CommonMethod.WriteLogs("GetCity-Error：" + ex.Message + "\r\n" + ex.Message + ex.StackTrace);
                return new
                {
                    ResultCode = (int)ApiResultCode.ServerError,
                    ResultMessage = EnumHelper.Instance.GetDescription(typeof(ApiResultCode), ApiResultCode.ServerError)
                };
            }
        }
    }
}
